package com.jy.modules.cims.loan;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.URLDecoder;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.controller.CimsBaseController;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.component.common.service.TCMmRaisePlanService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.dto.RaisePlanDto;
import com.jy.modules.cims.loan.service.RaisePlanService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
/**
 * 募集计划控制层
 * ClassName: RaisePlanController 
 * @Description: TODO
 * @author dell
 * @date 2015-9-8
 */
@Controller
@Scope("prototype")
@RequestMapping("/raisePlanCtrl")
public class RaisePlanController extends CimsBaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(RaisePlanController.class);
	

	@Autowired
	@Qualifier("com.jy.modules.cims.loan.service.RaisePlanService")
	private RaisePlanService raisePlanService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmRaisePlanService")
	private TCMmRaisePlanService tCMmRaisePlanService;
	
	/**
     * @Description 查询所有募集计划（仅可新建审批交互）列表（下拉框）
     * @param searchParams
     * @return   
     * List<RaisePlanDto>  
     * @throws
     * @author zhangmi
     * @date 2015-9-25
     */
	@RequestMapping(value = "/getSelectRaisePlanList")
	@ResponseBody
	public DataMsg getSelectRaisePlanList(HttpServletRequest request, RaisePlanDto dto, @ModelAttribute DataMsg dataMsg){
		List<RaisePlanDto> list;
		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("dto", dto);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(searchParams);
			PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
			params.setPageParameter(pageInfo);
			list = raisePlanService.getSelectRaisePlanList(params.getSearchParams());
			dataMsg.setData(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取募集计划列表失败！", e);
			dataMsg.failed(e.getMessage());
		}
		return dataMsg;
	}
	
	/**
     * @Description 查询所有募集计划（所有）列表（下拉框）
     * @param searchParams
     * @return   
     * List<RaisePlanDto>  
     * @throws
     * @author zhangmi
     * @date 2015-9-25
     */
	@RequestMapping(value = "/getSelectAllRaisePlanList")
	@ResponseBody
	public DataMsg getSelectAllRaisePlanList(HttpServletRequest request, RaisePlanDto dto, @ModelAttribute DataMsg dataMsg){
		List<RaisePlanDto> list;
		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("dto", dto);
			QueryReqBean params = new QueryReqBean();
			params.setSearchParams(searchParams);
			PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
			params.setPageParameter(pageInfo);
			list = raisePlanService.getRaisePlanList(params.getSearchParams());
			dataMsg.setData(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取募集计划列表失败！", e);
			dataMsg.failed(e.getMessage());
		}
		return dataMsg;
	}
	
	/**
     * @Description 募集计划查询列表
     * @param searchParams
     * @return   
     * List<RaisePlanDto>  
     * @throws
     * @author zhangmi
     * @date 2015-9-25
     */
	@RequestMapping(value = "/queryRaisePlanList")
    @ResponseBody
    public DataMsg queryListTCMmRaisePlan(HttpServletRequest request, RaisePlanDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<RaisePlanDto> list = raisePlanService.queryRaisePlanList(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
	
	/**
     * 
     * @Description 根据募集编号查询进件信息 状态 T_C_MM_LOAN_DETAIL.loan_each_status <>04
     * @param searchParams
     * @return   
     * List<RaisePlanDto>  
     * @throws
     * @author zhangmi
     * @date 2015-9-25
     */
	@RequestMapping(value = "/getjMsgByPlanId")
    @ResponseBody
	public DataMsg getjMsgByPlanId(HttpServletRequest request, RaisePlanDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	if(null==dto.getPlanId()){
    		dataMsg.failed("传参数有问题：募集计划编号为空！");
    		logger.error("传参数有问题：募集计划编号为空！");
    		return dataMsg;
    	}
		Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<RaisePlanDto> list = raisePlanService.searchJjMsgByPlanId(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
	
	/**
     * 导出募集计划
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/exportRaisePlan")
	@ResponseBody
    public void exportRaisePlan(HttpServletRequest request,HttpServletResponse response, RaisePlanDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	
		String fileName = "募集计划列表";
    	
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	String planName = URLDecoder.decode(request.getParameter("planName"),"UTF-8");
    	dto.setPlanName(planName);
		searchParams.put("dto", dto);
		
		List<RaisePlanDto> list = raisePlanService.searcRaisePlanListExport(searchParams);
		if(list!=null&&list.size()>60001){
			throw new Exception("导出最大支持60000条！");
		}
    	ExportAndImport<RaisePlanDto> exportAndImport = new ExportAndImport<RaisePlanDto>();
    	String columnCode = CimsConstant.RAISE_PLAN_CODE;
    	String columnName = CimsConstant.RAISE_PLAN_NAME;
		HSSFWorkbook workbook;
		workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
		write(workbook, fileName, response);
	}
    
    /**
	 * 页面输出
	 * 
	 * @param workbook
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

		try {
			
			response.setContentType("application/vnd.ms-excel");
			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			workbook.write(response.getOutputStream());
			response.getOutputStream().flush();
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		} finally {
			response.getOutputStream().close();
		}
	}
	
	/**
     * 更新募集计划项目总额
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/updateRaisePlanItemSum")
	@ResponseBody
    public DataMsg updateRaisePlanItemSum(HttpServletRequest request,HttpServletResponse response, @ModelAttribute DataMsg dataMsg) throws Exception{
    	
    	try {
			tCMmRaisePlanService.updateTCMmRaisePlanItemSum();
			dataMsg.setStatus("ok");
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.UPDATE_RAISE_PLAN_ITEM_SUM_FAIL + e.getMessage());
		}
    	
    	return dataMsg;
	}
	
}
